package com.primaryedu.ui.app.parentsch;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.MessagesBean;
import com.primaryedu.bean.QuestionsurveyBean;
import com.primaryedu.data.Contants;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.ui.app.messageboard.MessagboarddetailsActivity;
import com.primaryedu.ui.app.messageboard.MessagesListAdapter;
import com.primaryedu.widget.PullToRefreshView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Thomas on 2018/2/23.
 */

public class QuestionSurveyActivity extends BaseActivity implements View.OnClickListener, PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener {
    private PullToRefreshView pullToRefreshView;
    private ListView listView;
    private boolean fistenter = true;
    private int page = 1;
    private List<QuestionsurveyBean.DataBean.ListBean> questionsurveytempList = null;
    private QuestionsurveyAdapter questionsurveyAdapter;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != questionsurveyBean.getData().getList() && questionsurveyBean.getData().getList().size() != 0) {
                        if (questionsurveytempList == null) {
                            questionsurveytempList = questionsurveyBean.getData().getList();
                            questionsurveyAdapter = new QuestionsurveyAdapter(QuestionSurveyActivity.this, questionsurveytempList);
                            listView.setAdapter(questionsurveyAdapter);
                        }else {
                            questionsurveytempList.addAll(questionsurveyBean.getData().getList());
                            questionsurveyAdapter.notifyDataSetChanged();
                        }
                    }else {
                        if( questionsurveytempList!=null && questionsurveytempList.size()>0){
                            showToast( "亲，到底了");
                        }else{
                            showToast("亲，暂无数据");
                        }
                    }
//                    if (null != questionsurveytempList && questionsurveytempList.size() != 0) {
//                        questionsurveyAdapter = new QuestionsurveyAdapter(QuestionSurveyActivity.this, questionsurveytempList);
//                        listView.setAdapter(questionsurveyAdapter);
//                    }
                    break;
                case 1002:
//                    if (questionsurveytempList != null && questionsurveytempList.size() != 0) {
//                        questionsurveyAdapter.updateVoteView(questionsurveytempList);
//                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };
    private QuestionsurveyBean questionsurveyBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_questionsurvey);
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_questionsurvey;
    }

    @Override
    protected void initView() {
        ((TextView) findViewById(R.id.title)).setText("问卷调查");
        findViewById(R.id.back).setOnClickListener(this);
        listView = (ListView) this.findViewById(R.id.listView);


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                QuestionsurveyBean.DataBean.ListBean vb = questionsurveytempList.get(position);
                Intent intent = new Intent(QuestionSurveyActivity.this, QuestionActivity.class);
                intent.putExtra("id", vb.getId());
                intent.putExtra("name", vb.getName());

                startActivity(intent);
            }
        });
        pullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());
    }

    @Override
    protected void initData() {
        requestQuestionsruveyList(fistenter);
    }

    private void requestQuestionsruveyList(boolean fistenter) {
        if (fistenter) {
            showLoading("加载中...");
        }
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.questionsurveypageList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=questionsurveypageList=======" + response);
                        Gson gson = new Gson();
                        questionsurveyBean = gson.fromJson(response, QuestionsurveyBean.class);
                        if (questionsurveyBean.getResult() == 1) {
                            handler.sendEmptyMessage(1001);
                        }
                       /* try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");
                                Gson gson = new Gson();
                                questionsurveyBean = gson.fromJson(response, QuestionsurveyBean.class);
//                                questionsurveyLists = new Gson().fromJson(listStr,
//                                        new TypeToken<List<QuestionsurveyBean.DataBean.ListBean>>() {
//                                        }.getType());
//								if (uploadMore) {
//									loadmoremasterboxList.addAll(masterboxLists);
//									handler.sendEmptyMessage(1002) ;
//									uploadMore = false;
//								}else {
//                                questionsurveytempList.clear();
//                                questionsurveytempList.addAll(questionsurveyLists);
                                handler.sendEmptyMessage(1001);
////								}
                                System.out.println("leaveLists==" + listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }*/
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("访问失败，请重新刷新下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
//				map.put("status", "1");
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    private void requestmorequestionsurveyList() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.questionsurveypageList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("response=questionsurveypageList=======" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {

                                String data = json.getString("data");
                                if (data.contains("list")) {
                                    JSONObject listObj = new JSONObject(data);
                                    String listStr = listObj.getString("list");

//                                    questionsurveyLists = new Gson().fromJson(listStr,
//                                            new TypeToken<List<QuestionsurveyBean.DataBean.ListBean>>() {
//                                            }.getType());

//                                    questionsurveytempList.clear();
//                                    questionsurveytempList.addAll(questionsurveyLists);
                                    handler.sendEmptyMessage(1002);
                                } else {
                                    showToast("已经加载完全部数据！");
                                }
//								System.out.println("leaveLists=="+listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
//				map.put("status", "1");
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            default:
                break;
        }
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
//				uploadMore = true;
                page++;
                requestQuestionsruveyList(false);
                pullToRefreshView.onFooterRefreshComplete();

            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                questionsurveyAdapter = null;
                questionsurveytempList = null;
                requestQuestionsruveyList(false);
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                Toast.makeText(QuestionSurveyActivity.this, "数据刷新完成!", Toast.LENGTH_LONG).show();
            }

        }, 1500);
    }
}
